package ute.mvc.dao;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ute.mvc.model.OpenCourse;
import ute.mvc.model.User;

@Repository("userDAO")
public class UserDAOImpl implements UserDAO {
	@Autowired
	private SessionFactory sessionFactory;

	public User getUserByEmail(String email) {
		return (User) sessionFactory.getCurrentSession()
				.createCriteria(User.class)
				.add(Restrictions.eq("email", email))
				.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
				.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	public List<User> getAllUser() {
		return sessionFactory.getCurrentSession().createCriteria(User.class)
				.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
				.setFetchMode("listClass", FetchMode.EAGER).list();
	}

	@SuppressWarnings("unchecked")
	public List<User> findUserByEmail(String email) {
		return sessionFactory.getCurrentSession().createCriteria(User.class)
				.add(Restrictions.like("email", "%" + email + "%"))
				.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
	}

	public void addUser(User user) {
		sessionFactory.getCurrentSession().save(user);

	}

	public void updateUser(User user) {
		sessionFactory.getCurrentSession().merge(user);
	}

	public void deleteUser(User user) {
		sessionFactory.getCurrentSession().delete(user);
	}

	public User getUserById(int id) {
		return (User) sessionFactory.getCurrentSession().get(User.class, id);
	}

	@SuppressWarnings("rawtypes")
	public String getUserPassword(int id) {
		// TODO Auto-generated method stub
		String password = "";
		List list = sessionFactory.getCurrentSession()
				.createCriteria(User.class).add(Restrictions.idEq(id))
				.setProjection(Projections.property("password")).list();
		Iterator it = list.iterator();

		while (it.hasNext()) {
			password = (String) it.next();
		}
		return password;
	}

	@SuppressWarnings("unchecked")
	public List<OpenCourse> getListOpenCourseWithLecturerId(int lecturerId) {
		return sessionFactory.getCurrentSession()
				.createCriteria(OpenCourse.class)
				.createCriteria("listLecturer")
				.add(Restrictions.eq("userId", lecturerId))
				.list();
	}

	public List<User> getAllStudent() {
		return sessionFactory.getCurrentSession().createCriteria(User.class)
				.add(Restrictions.eq("role", 3))
				.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
				.setFetchMode("listClass", FetchMode.EAGER)
				.list();
	}
}
